package lime.xquery.view;

import lime.common.DOMUtils;
import lime.common.UIUtils;
import lime.xquery.widget.XQueryDataResult;
import lime.xquery.widget.XQueryErrorResult;
import lime.xquery.widget.XQueryTextResult;
import lime.xquery.widget.XQueryXhtmlResult;
import lime.xquery.widget.XQueryXmlResult;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;
import org.w3c.dom.Document;

public class XQueryResultsView extends ViewPart {

	public static final String ID = "lime.xquery.view.results";

	private Composite parent;

	@Override
	public void createPartControl(Composite parent) {
		this.parent = parent;
	}

	@Override
	public void setFocus() {
		// Empty
	}

	public void update(final String paramText, final XQueryResult paramResult) {

		// Make a defensive copy of the result so we can modify it if necessary
		XQueryResult result = paramResult;

		UIUtils.clear(parent);
		
		// Determine based on the actual XQuery result how it should be displayed
		if (result.equals(XQueryResult.AUTO)) {
			try {
				Document doc = DOMUtils.parse(paramText);
				String documentElementName = doc.getDocumentElement().getNodeName();
				if (documentElementName.equals("data")) {
					result = XQueryResult.DATA;
				} else if (documentElementName.equals("html") || documentElementName.equals("xhtml")) {
					result = XQueryResult.XHTML;
				} else {
					result = XQueryResult.XML;
				}
			} catch (Exception e) {
				// Unable to parse text as XML; assume the result is plain text.
				result = XQueryResult.TEXT;
			}
		}

		switch (result) {

			case TEXT:
				XQueryTextResult textComposite = new XQueryTextResult(parent, SWT.NONE);
				textComposite.update(paramText);
				break;

			case XML:
				XQueryXmlResult xmlComposite = new XQueryXmlResult(parent, SWT.NONE);
				xmlComposite.update(paramText);
				break;

			case XHTML:
				XQueryXhtmlResult xhtmlComposite = new XQueryXhtmlResult(parent, SWT.NONE);
				xhtmlComposite.update(paramText);
				break;

			case DATA:
				XQueryDataResult dataComposite = new XQueryDataResult(parent, SWT.NONE);
				dataComposite.update(paramText);
				break;

			case ERROR:
				XQueryErrorResult errorComposite = new XQueryErrorResult(parent, SWT.NONE);
				errorComposite.update(paramText);
				break;

			default:
				break;
		}

		parent.layout();
	}
}
